using AutoMapper;
using MediatR;
using SmartApplication.Api.Applient.Command.Feed;
using SmartApplication.ApiCode;
using SmartApplication.Domain.Entity;
using SmartApplication.Infrastructure.Instrument;
using Yitter.IdGenerator;

namespace SmartApplication.Api.Applient.CommandHandler.Feed
{
    public class AddHealthHandler : IRequestHandler<AddHealthCommand, ApiResult<int>>
    {
        public AddHealthHandler(IBaseRepository<HealthModel> healthRepository, IMapper mapper)
        {
            HealthRepository = healthRepository;
            Mapper = mapper;
        }

        public IBaseRepository<HealthModel> HealthRepository { get; }
        public IMapper Mapper { get; }

        /// <summary>
        /// 添加保健信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddHealthCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();

            var health = Mapper.Map<HealthModel>(request);
            health.Id = YitIdHelper.NextId();

            var add = await HealthRepository.AddAsync(health);
            if (add > 0)
            {
                res.Code = EnumCode.Success;
                res.Message = "添加保健信息成功";
                res.Data = add;
                return res;
            }
            else
            {
                res.Code = EnumCode.Fail;
                res.Message = "添加保健信息失败";
                res.Data = add;
                return res;
            }
        }
    }
}